package com.lehecai.core.service.impl.queue;

import com.lehecai.core.service.queue.JmsQueueService;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import javax.jms.*;
import java.io.Serializable;
import java.util.Map;

public class ActiveMQJmsQueueServiceImpl implements JmsQueueService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	private JmsTemplate jmsTemplate;

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

    @Override
    public Object receiveAndConvert(String queue) throws Exception {
        return jmsTemplate.receiveAndConvert(new ActiveMQQueue(queue));
    }

    protected void send(String queue, MessageCreator messageCreator) throws Exception {
        jmsTemplate.send(new ActiveMQQueue(queue), messageCreator);
    }

    @Override
    public void send(String queue) throws Exception {
        this.send(queue, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(StringUtils.EMPTY);
            }
        });
    }

    @Override
    public void send(String queue, final Map<String, Object> message) throws Exception {
        this.send(queue, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();

                for(String item : message.keySet()){
                    mapMessage.setObject(item, message.get(item));
                }
                return mapMessage;
            }
        });
	}

    @Override
	public void send(String queue, final Serializable message) throws Exception {
        this.send(new ActiveMQQueue(queue), message);
	}

    @Override
    public void send(String queue, String message) throws Exception {
        this.send(new ActiveMQQueue(queue), message);
    }

    @Override
    public void send(Queue queue, final Serializable message) throws Exception {
        jmsTemplate.send(queue, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage(message);
            }
        });
    }

    @Override
    public void send(Queue queue, final String message) throws Exception {
        jmsTemplate.send(queue, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });
    }
}
